package com.rdgzs.authority.security;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.rdgzs.authority.entity.User;
import com.rdgzs.authority.service.UserService;
import com.rdgzs.framework.constant.SysConstants;
import com.rdgzs.framework.utilsTools.ConfigPropertiesUtils;
import com.rdgzs.framework.utilsTools.EncryptUtils;

public class DbShiroRealm extends AuthorizingRealm {

	@Override
	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.【授权】
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRole("admin");
		info.addStringPermission("admin");
		return info;
		// return null;
	}

	/**
	 * 认证回调函数,登录时调用.【认证】
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		Session session = SecurityUtils.getSubject().getSession();
		Integer failedCount = (Integer) session.getAttribute(SysConstants.LOGIN_FAILED_COUNT);
		String captcha = (String) session.getAttribute(SysConstants.CAPTCHA);
		String adminAcount = ConfigPropertiesUtils.get(SysConstants.ADMIN_ACCOUNT);
		String adminPassword = ConfigPropertiesUtils.get(SysConstants.ADMIN_PASSWORD);
		String adminSalt = ConfigPropertiesUtils.get(SysConstants.ADMIN_SALT);
		String adminName = ConfigPropertiesUtils.get(SysConstants.ADMIN_NAME);
		SimpleAuthenticationInfo auth = null;

		// UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;
		String username = token.getUsername();
		String password = new String(token.getPassword());

		if (captcha != null && !captcha.equalsIgnoreCase(token.getCaptcha())) {
			failedCount = (failedCount == null ? 0 : failedCount);
			session.setAttribute(SysConstants.LOGIN_FAILED_COUNT, ++failedCount);
			throw new IncorrectCaptchaException("验证码错误！");
		}

		if (failedCount != null && failedCount > 3) {
			throw new IncorrectCaptchaException("登陆错误已大于3次！");
		}
		if (username.equals(adminAcount)) {
			try {
				// System.out.println(EncryptUtils.MD5(password,
				// adminSalt).toCharArray());
				token.setPassword(EncryptUtils.MD5(password, adminSalt).toCharArray());
				auth = new SimpleAuthenticationInfo(adminAcount, adminPassword, getName());
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				List<User> users = userService.query(SysConstants.USER_COL_ID, username);
				if (users.size() > 0) {
					User user = users.get(0);
					if (StringUtils.isNotBlank(user.getSalt())) {
						token.setPassword(EncryptUtils.MD5(password, user.getSalt()).toCharArray());
					} else {
						token.setPassword(EncryptUtils.MD5(password).toCharArray());
					}
					auth = new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(), getName());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 用户名密码验证
		// return auth;

		// 返回一个默认的用户密码
		return new SimpleAuthenticationInfo("admin", "admin", getName());
	}

	private UserService userService;

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
